import storage from "@/utils/storage"
import constant from '@/utils/constant'
import { getToken,setToken,removeToken } from "@/utils/auth.js"
import { login,getInfo,logout } from "@/api/login"


const user = {
	state:{
		id: storage.get(constant.id),
		token:getToken(),
		name: storage.get(constant.name),
		avatar: storage.get(constant.avatar),
		roles: storage.get(constant.roles),
		permissions: storage.get(constant.permissions)
	},
	mutations:{
		SET_TOKEN:(state,token)=> {
			state.token = token
		},
		SET_NAME:(state,name)=>{
			state.name = name
			storage.set(constant.name,name)
		},
		SET_ID:(state,id)=>{
			state.id = id
			storage.set(constant.id,id)
		},
		SET_AVATAR:(state,avatar)=>{
			state.avatar = avatar
			storage.set(constant.avatar,avatar)
		},
		SET_ROLES:(state,roles)=>{
			state.roles = roles
			storage.set(constant.roles,roles)
		},
		SET_PERMISSIONS:(state,permissions)=>{
			state.permissions = permissions
			storage.set(constant.permissions,permissions)
		}
	},
	actions:{
		//登录
		Login({commit},userInfo){
			return new Promise((resolve,reject)=> {
				login(userInfo).then(res=> {
					setToken(res.data.token)
					commit("SET_TOKEN",res.data.token)
					resolve()
				}).catch(error=> {
					console.log("我失败了")
					reject(error)
				})
			})
		},
		//获取用户信息
		GetUserInfo({commit}){
			return new Promise((resolve,reject)=> {
				getInfo().then(res=>{
					commit("SET_ID",res.data.id)
					commit("SET_NAME",res.data.name)
					commit("SET_AVATAR",res.data.avatar)
					commit("SET_ROLES",res.data.roleList)
					commit("SET_PERMISSIONS",res.data.permissions)
					resolve(res.data)
				}).catch(error=> {
					reject(error)
				})
			})
		},
		//登出
		LogOut({commit}){
			return new Promise((resolve,reject)=> {
				commit('SET_TOKEN', '')
				commit('SET_ROLES', [])
				commit('SET_PERMISSIONS', [])
				removeToken()
				storage.clean()
				resolve()
			})
		}
	}
}

export default user
